<template>
  <div class="">
    <!-- 面包屑导航区域 开始 -->
    <el-breadcrumb class="breadcrumb" separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>菜单设置</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 面包屑导航区域 开始 -->
    <el-card class="box-card">
      <div>
        <el-input
          style="width:240px;margin-right:30px"
          placeholder="请输入一级菜单名称"
          v-model="condition.search"
          clearable
        >
        </el-input>
        <el-button
          type="primary"
          @click="searchMenuName"
          class="my-el-button el-icon-search"
          >查询</el-button
        >
        <el-button
          class="el-icon-plus addMenu"
          size="medium"
          @click="addMenuOne"
          type="success"
          >添加一级菜单</el-button
        >
      </div>
      <el-table v-loading="loading" :data="tableData" style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="props">
            <div class="drag-item-title ">
              <el-row>
                <el-col class="line" :span="4">
                  二级菜单名
                </el-col>
                <el-col class="line" :span="4">
                  二级菜单url
                </el-col>
                <el-col class="line" :span="4">
                  二级菜单图标
                </el-col>
                <el-col :span="3">
                  操作
                </el-col>
              </el-row>
            </div>
            <div
              v-for="(item, i) in props.row.menuList"
              :key="item._id"
              class="drag-item  text item"
            >
              <el-row>
                <el-col class="line" :span="4"
                  >&nbsp;{{ item.menuName }}</el-col
                >
                <el-col class="line" :span="4">/{{ item.menuUrl }}</el-col>
                <el-col class="line" :span="4">
                  <img
                    style="width:20px;height:20px"
                    class="icon"
                    :src="item.menuIcon"
                  />
                </el-col>
                <el-col :span="3">
                  <el-button
                    v-if="item.is_system != 1"
                    type="text"
                    size="mini"
                    class="my-el-button-text"
                    @click="deleCode(i, item, props.row)"
                    >删除</el-button
                  >
                  <el-button
                    v-if="item.is_system != 1"
                    type="text"
                    size="mini"
                    class="my-el-button-text"
                    @click="enditCode(i, item, props.row)"
                    >修改</el-button
                  >
                </el-col>
              </el-row>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="菜单名称" prop="menuName"> </el-table-column>
        <el-table-column label="菜单url" prop="">
          <template slot-scope="scope"> /{{ scope.row.menuUrl }} </template>
        </el-table-column>
        <el-table-column label="菜单图标" prop="">
          <template slot-scope="scope">
            <img style="width:20px;height:20px" :src="scope.row.menuIcon" />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              class="my-el-button-default"
              size="mini"
              @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="danger"
              :disabled="scope.row.menuList.length > 0"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
            <el-button
              size="mini"
              class="el-icon-plus"
              type="success"
              @click="handleAdd(scope.$index, scope.row)"
              >添加二级菜单</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 开始-->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="condition.page"
          :page-sizes="[5, 10, 15, 30]"
          :page-size="condition.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
      <!-- 分页 结束-->
    </el-card>
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="ruleForm" :model="form">
        <el-form-item
          label="菜单名称"
          prop="menuName"
          :label-width="formLabelWidth"
        >
          <el-input v-model="form.menuName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          label="菜单url"
          prop="menuUrl"
          :label-width="formLabelWidth"
        >
          <el-input
            :disabled="flag == 3 || flag == 4"
            v-model="form.menuUrl"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="菜单Icon" :label-width="formLabelWidth">
          <el-upload
            ref="uploadImg"
            class="avatar-uploader"
            action="#"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :on-change="changeUpload"
            :file-list="fileList"
            :http-request="uploadImg"
            accept="image/png, image/jpeg,image/jpg,.svg"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button
          class="my-el-button-default"
          @click="dialogFormVisible = false"
          >取 消</el-button
        >
        <el-button class="my-el-button" type="primary" @click="determine"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { uploadImg, uploadImgTrue } from '@/network/bookManager'
import {
  queryMenuList,
  addMenu,
  removeMenuById,
  updateMenuById,
  queryMenuListTotal
} from '@/network/authorityManager'
export default {
  data() {
    return {
      tableData: [],
      // 弹窗标题
      title: '',
      // 弹窗 属性控制
      dialogFormVisible: false,
      form: {
        _id: '',
        menuName: '',
        menuUrl: '',
        parentId: '0',
        menuIcon: ''
      },
      formLabelWidth: '120px',
      // 图片展示地址
      imageUrl: '',
      // 文件集合
      fileList: [],
      file: null, // 图片文件
      rules: {
        menuName: [
          { required: true, message: '请输入菜单名称', trigger: 'blur' }
        ],
        menuUrl: [
          { required: true, message: '请输入菜单地址', trigger: 'blur' }
        ]
      },
      // 按钮标记  1添加 一级  2添加二级 3修改一级  4修改二级
      flag: -1,
      // table页面加载
      loading: false,
      // 选中的一级菜单对象
      menuListOne: {},
      selectIndex: -1,
      // 查询条件
      condition: {
        page: 1,
        size: 10,
        search: ''
      },
      total: 0
    }
  },
  methods: {
    // 获取 菜单列表
    queryMenuList() {
      this.loading = true
      // 查询 菜单
      queryMenuList(this.condition).then(res => {
        console.info(JSON.parse(res.resp_data).list)
        this.tableData = JSON.parse(res.resp_data).list
        this.loading = false
      })
      // 获取总条数
      queryMenuListTotal(this.condition).then(res => {
        this.total = JSON.parse(res.resp_data).list[0].total
      })
    },
    // 添加一级菜单
    addMenuOne() {
      this.resetFields()
      this.menuListOne = {}
      this.form.parentId = '0'
      this.flag = 1
      this.title = '添加一级菜单'
      this.dialogFormVisible = true
    },
    // 添加二级菜单
    handleAdd(index, row) {
      this.resetFields()
      this.title = '添加二级菜单'
      this.flag = 2
      this.form.parentId = row._id
      this.menuListOne = row
      this.dialogFormVisible = true
      console.info(row)
    },
    // 图片上传成功后的回调
    handleAvatarSuccess() {
      this.$message.success('图片上传完成')
    },
    // 图片上传 前的回调
    beforeAvatarUpload(file) {
      this.$refs.ruleForm.validate(valid => {
        if (!valid) return false
      })
      console.log(file)
    },
    //文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
    changeUpload(file, fileList) {
      this.$refs.ruleForm.validate(valid => {
        if (!valid) return

        this.file = file
        const isJPG = new RegExp('^image/.*$').test(file.raw.type)
        const isLt2M = file.raw.size / 1024 / 1024 < 2
        this.fileList = fileList
        if (isJPG && isLt2M) {
          this.imageUrl = URL.createObjectURL(file.raw)
          console.info('this.imageUrl:' + this.imageUrl)
          this.fileList.length > 1 ? this.fileList.splice(0, 1) : ''
          this.oldFileUid = file.uid
        } else {
          this.fileList.length > 1
            ? this.fileList.splice(1, 1)
            : this.fileList.splice(0, 1)
          if (!isJPG) {
            this.$message.error('只能上传图片哦')
          } else if (!isLt2M) {
            this.$message.error('上传头像图片大小不能超过 2MB!')
          }
        }
      })
    },
    // 自定义上传方法
    async uploadImg() {
      let file = this.file
      const isJPG = new RegExp('^image/.*$').test(file.raw.type)
      if (!isJPG) return
      const imgName =
        `menuIcon/${this.menuListOne ? this.menuListOne.menuName + `/` : ``}${
          this.form.menuName
        }/` +
        new Date().getTime() +
        file.name
      let res = await uploadImg(imgName)
      // 将返回的地址 处理成代理地址
      let website = res.url.substring(0, res.url.indexOf('com') + 3)
      let trueUrl = res.url.replace(website, '/img')
      // 将数据封装成 formData
      const formData = new FormData()
      formData.append('Signature', res.authorization)
      formData.append('key', imgName)
      formData.append('x-cos-security-token', res.token)
      formData.append('x-cos-meta-fileid', res.cos_file_id)
      formData.append('file', file.raw)
      uploadImgTrue(trueUrl, formData) // 最后一步上传图片
      const imgUrl = `https://7a68-zhuma-mbnti-1302831863.tcb.qcloud.la/${imgName}`
      this.form.menuIcon = imgUrl // 将图片路径 存入表单对象中
      console.info(imgUrl)
    },
    // 确定按钮
    determine() {
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          console.info(this.flag)
          if (this.flag == 1 || this.flag == 2) {
            if (!this.form.menuIcon)
              return this.$message.warning('等待图片上传完成')
            this.loading = true
            addMenu(this.form).then(res => {
              if (this.flag == 1) {
                if (this.tableData.length < this.condition.size) {
                  this.form._id = res.id_list[0]
                  this.form.menuList = []
                  this.tableData.push(this.form)
                }
              } else {
                this.form._id = res.id_list[0]
                this.menuListOne.menuList.push(this.form)
              }
              this.loading = false
              this.dialogFormVisible = false
            })

            return
          }
          this.$confirm('此操作将永久修改该数据, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              updateMenuById(this.form)
              if (this.flag == 3) {
                this.tableData.splice(this.selectIndex, 1, this.form)
              } else {
                this.menuListOne.menuList.splice(this.selectIndex, 1, this.form)
              }
              this.$message.success('修改成功')
              this.dialogFormVisible = false
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
              })
            })
        }
      })
    },
    // 删除按钮
    handleDelete(index, row) {
      this.$confirm('此操作将永久删除该菜单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          sessionStorage.removeItem('menuList')
          removeMenuById(row._id).then(() => {
            queryMenuListTotal(this.condition).then(res => {
              this.total = JSON.parse(res.resp_data).list[0].total
            })
          })
          this.tableData.splice(index, 1)
          this.$message.success('删除成功')
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      console.info(row)
    },
    // 删除二级菜单
    deleCode(index, item, table) {
      this.$confirm('此操作将永久删除该菜单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          sessionStorage.removeItem('menuList')
          removeMenuById(item._id)
          console.info(table)
          table.menuList.splice(index, 1)
          this.$message.success('删除成功')
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    // 重置表单
    resetFields() {
      this.form = {
        menuName: '',
        menuUrl: '',
        parentId: '0',
        menuIcon: ''
      }
      this.imageUrl = ''
    },
    // 修改按钮
    handleEdit(index, row) {
      this.resetFields()
      this.flag = 3
      this.selectIndex = index
      this.title = '修改一级菜单'
      this.form = JSON.parse(JSON.stringify(row))
      this.imageUrl = this.form.menuIcon
      this.dialogFormVisible = true
      console.info(row)
    },
    // 修改二级菜单
    enditCode(index, item, table) {
      this.resetFields()
      console.info(index)
      this.title = '修改二级菜单'
      this.flag = 4
      console.info(item)
      this.form = JSON.parse(JSON.stringify(item))
      console.info(this.form)
      this.imageUrl = this.form.menuIcon
      this.menuListOne = table
      this.selectIndex = index
      this.dialogFormVisible = true
    },
    // 搜索按钮
    searchMenuName() {
      this.queryMenuList()
    },
    // size数据改变
    handleSizeChange(val) {
      this.condition.size = val
    },
    // 翻页
    handleCurrentChange(val) {
      this.condition.page = val
    }
  },
  // 页面加载时 调用
  mounted() {
    this.queryMenuList()
  },
  // 监听查询条件
  watch: {
    'condition.page': {
      // 页码发生变化
      handler: function() {
        this.queryMenuList()
      }
    },
    'condition.size': {
      // 每页多少条发生变化
      handler: function() {
        this.queryMenuList()
      }
    }
  }
}
</script>
<style lang="less" scoped>
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
.drag-item {
  padding-top: 7px;
  border-top: 1px solid rgb(226, 223, 223);
}
.drag-item:last-child {
  border-bottom: 1px solid rgb(226, 223, 223);
}
.drag-item-title {
  border-top: none;
  padding-bottom: 10px;
}
.box-card {
  margin-top: 20px;
}
.el-col-6 {
  width: 200px;
  height: 100%;
}
.chapterBody {
  margin: 10px 10px;
}
.drag-item-title {
  color: #67c23a;
}
.addMenu {
  float: right;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
  border: 1px dashed #fd7c27;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
